<?php
/**
 * This is the template for generating a controller class file.
 */
use yii\db\ActiveRecordInterface;
use yii\helpers\StringHelper;

/* @var $this yii\web\View */
/* @var $generator yii\gii\generators\controller\Generator sssss*/

$controllerClass = StringHelper::basename($generator->controllerClass);
$modelClass = StringHelper::basename($generator->modelClass);

echo "<?php\n";
?>
namespace <?= StringHelper::dirname(ltrim($generator->controllerClass, '\\')) ?>;

use <?= ltrim($generator->modelClass, '\\') ?>;
use apiadmin\CoreController;

class <?= StringHelper::basename($generator->controllerClass) ?> extends CoreController
{

	## 数据列表 
	public function actionList()
	{
		$whereArr = $this->getWhere();
		$params = array(
			'field'	=> ['*'],
			'page'	=> $this->request('page',1),
			'limit'	=> $this->request('page_size',10),
			'order' => 'id desc',
		);

		$data = <?= $modelClass ?>::dataList($whereArr, $params);
		$totalNums = <?= $modelClass ?>::$totalNums;
		$this->out('数据列表', $data, ['totalNums' => $totalNums]);
	}

	## 组装条件
	private function getWhere()
	{
		$where = $and = [];
		$search = $this->request('search');
		$search = $search?json_decode($search,1):'';
		if(!$search) return $whereArr;

		foreach($search as $key => $val)
		{
			if(empty($val)) continue;
			if($k=='date')
			{
				if(!$val['0'] || !$val['1']) continue;
				$and[] = ['between', 'create_time', strtotime($val[0]),strtotime($val[1])]; 
			}else
			{
				$where[$key] = $val;
			}			
		}
		return ['where' => $where, 'and' => $and];
	}


	## 编辑/添加
	public function actionEdit()
	{
		$id = $this->request('id');
		
		$model = new <?= $modelClass ?>;
		if($id)
		{
			$model = <?= $modelClass ?>::findOne(['id' => $id]);
			if(!$model) $this->error('参数有误');
		}else{
			$this->request['create_time'] = time();
		}
		$this->request['update_time'] = time();

		if(!$model->load($this->request, '') || !$model->validate() || !$model->save(false)){
			$msg = $model::outError($model->getErrors());  
			$this->error($msg);
		}

		$this->out('操作成功');
	}


	## 删除
	public function actionDel()
	{
		if(!$id = $this->request('id')) $this->error('参数有误');

		$res = <?= $modelClass ?>::deleteAll(['id'=>$id]);

		if(!$res) $this->error('删除失败');
		$this->out('删除成功');
	}
}
